/**
 * 数据库API使用示例
 * 展示如何在客户端组件中使用API而不是直接数据库操作
 */

'use client';

import { useState, useEffect } from 'react';
import { VideoApiService, CategoryApiService, DatabaseApiService } from '@/app/lib/api-client';
import type { Video, Category } from '@/app/lib/api-client';

// 示例：视频列表组件
export function VideoList() {
  const [videos, setVideos] = useState<Video[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadVideos();
  }, []);

  const loadVideos = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const response = await VideoApiService.getAllVideos(20, 0);
      
      if (response.success && response.data) {
        setVideos(response.data);
      } else {
        setError(response.message || '加载视频失败');
      }
    } catch (err) {
      setError('网络请求失败');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <div className="p-4">加载中...</div>;
  }

  if (error) {
    return (
      <div className="p-4 text-red-600">
        错误: {error}
        <button 
          onClick={loadVideos}
          className="ml-2 px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600"
        >
          重试
        </button>
      </div>
    );
  }

  return (
    <div className="p-4">
      <h2 className="text-xl font-bold mb-4">视频列表</h2>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {videos.map((video) => (
          <div key={video.id} className="border rounded-lg p-4">
            <h3 className="font-semibold">{video.title}</h3>
            <p className="text-sm text-gray-600">{video.category}</p>
            <p className="text-sm text-gray-500">{video.description}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

// 示例：分类列表组件
export function CategoryList() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadCategories();
  }, []);

  const loadCategories = async () => {
    try {
      setLoading(true);
      const response = await CategoryApiService.getAllCategories();
      
      if (response.success && response.data) {
        setCategories(response.data);
      }
    } catch (err) {
      console.error('加载分类失败:', err);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <div className="p-4">加载分类中...</div>;
  }

  return (
    <div className="p-4">
      <h2 className="text-xl font-bold mb-4">分类列表</h2>
      <div className="space-y-2">
        {categories.map((category) => (
          <div key={category.id} className="flex justify-between items-center p-2 border rounded">
            <div>
              <span className="font-medium">{category.name}</span>
              <span className="ml-2 text-sm text-gray-500">({category.video_count} 个视频)</span>
            </div>
            <span className="text-sm text-gray-400">{category.description}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// 示例：搜索组件
export function VideoSearch() {
  const [keyword, setKeyword] = useState('');
  const [results, setResults] = useState<Video[]>([]);
  const [loading, setLoading] = useState(false);

  const handleSearch = async () => {
    if (!keyword.trim()) return;

    try {
      setLoading(true);
      const response = await VideoApiService.searchVideos(keyword, 10, 0);
      
      if (response.success && response.data) {
        setResults(response.data);
      }
    } catch (err) {
      console.error('搜索失败:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-4">
      <div className="flex gap-2 mb-4">
        <input
          type="text"
          value={keyword}
          onChange={(e) => setKeyword(e.target.value)}
          placeholder="搜索视频..."
          className="flex-1 px-3 py-2 border rounded"
          onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
        />
        <button
          onClick={handleSearch}
          disabled={loading}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50"
        >
          {loading ? '搜索中...' : '搜索'}
        </button>
      </div>

      {results.length > 0 && (
        <div>
          <h3 className="text-lg font-semibold mb-2">搜索结果:</h3>
          <div className="space-y-2">
            {results.map((video) => (
              <div key={video.id} className="p-2 border rounded">
                <h4 className="font-medium">{video.title}</h4>
                <p className="text-sm text-gray-600">{video.category}</p>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// 示例：数据库管理组件
export function DatabaseManager() {
  const [status, setStatus] = useState<string>('未知');
  const [loading, setLoading] = useState(false);

  const testConnection = async () => {
    try {
      setLoading(true);
      const response = await DatabaseApiService.testConnection();
      
      if (response.success) {
        setStatus(response.data?.connected ? '已连接' : '未连接');
      } else {
        setStatus('连接失败');
      }
    } catch (err) {
      setStatus('测试失败');
    } finally {
      setLoading(false);
    }
  };

  const initDatabase = async () => {
    try {
      setLoading(true);
      const response = await DatabaseApiService.initializeDatabase();
      
      if (response.success) {
        setStatus('初始化完成');
      } else {
        setStatus('初始化失败');
      }
    } catch (err) {
      setStatus('初始化失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-4">
      <h2 className="text-xl font-bold mb-4">数据库管理</h2>
      <div className="space-y-4">
        <div>
          <p>状态: <span className="font-medium">{status}</span></p>
        </div>
        <div className="flex gap-2">
          <button
            onClick={testConnection}
            disabled={loading}
            className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 disabled:opacity-50"
          >
            {loading ? '测试中...' : '测试连接'}
          </button>
          <button
            onClick={initDatabase}
            disabled={loading}
            className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50"
          >
            {loading ? '初始化中...' : '初始化数据库'}
          </button>
        </div>
      </div>
    </div>
  );
}

// 示例：完整的视频管理页面
export function VideoManagementPage() {
  return (
    <div className="max-w-6xl mx-auto p-6">
      <h1 className="text-3xl font-bold mb-8">视频管理系统</h1>
      
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <div>
          <VideoList />
        </div>
        <div>
          <CategoryList />
        </div>
      </div>
      
      <div className="mt-8">
        <VideoSearch />
      </div>
      
      <div className="mt-8">
        <DatabaseManager />
      </div>
    </div>
  );
}
